var common = require('../../../../utils/common.js');
var app = getApp();


Page({
	data:{
		__PUBLIC__:app.__PUBLIC__,
        show:false,
        display:false,
		deviceId:"",
        serviceId:"",
        notifyCharacteristicsId:"",
        writeCharacteristicsId:"",
        readCharacteristicsId:""
	},
    onLoad:function(options){
        this.setData({equipment_id:options.equipment_id}); 
    },
    unLock:function(event){  
        let buff = new ArrayBuffer(8);
        let dataView = new DataView(buff);

        let str = "12172111";
        for (var i = 0; i < str.length; i++) {  
            dataView.setInt8(i, str[i].charCodeAt());  
        }
            this.send(buff);
    },
    Lock:function(){
        let buff = new ArrayBuffer(8);
        let dataView = new DataView(buff);

        let str = "12172114";
        for (var i = 0; i < str.length; i++) {  
            dataView.setInt8(i, str[i].charCodeAt());  
        }
    	this.send(buff);
    },
    Ignite:function(){
        let buff = new ArrayBuffer(8);
        let dataView = new DataView(buff);

        let str = "12172112";
        for (var i = 0; i < str.length; i++) {  
            dataView.setInt8(i, str[i].charCodeAt());  
        }
        this.send(buff);
    },
    unIgnite:function(){
        let buff = new ArrayBuffer(8);
        let dataView = new DataView(buff);

        let str = "12172113";
        for (var i = 0; i < str.length; i++) {  
            dataView.setInt8(i, str[i].charCodeAt());  
        }
        this.send(buff);
    },
    initOperate:function(){
    	if (wx.openBluetoothAdapter) {  
    		this.blueInit()
            .then(res=>{
                console.log('初始化成功');
                this.blueStatus()
                .then(res=>{
                    this.setData({    
                        status: res.available ? "可用。" : "不可用。",  
                    })
                    this.searchBlueTooth()
                    .then(res=>{
                        this.gainBlueTooth()
                        .then(res=>{
                            console.log(res);
                            this.var_dump(res.devices);
                            this.setData({
                                show:true
                            }) 
                        })
                        .catch(e=>{
                            console.log(e);
                            wx.showToast({
                                title: '获取设备失败,请重启小程序',
                                icon: 'none',
                                duration: 1000
                            });
                        })
                    })
                    .catch(e=>{
                        console.log(e);
                        wx.showToast({
                            title: '多次搜索,请重启小程序',
                            icon: 'none',
                            duration: 1000
                        });
                    })
                })
                .catch(e=>{
                    console.log(e);
                    wx.showToast({
                        title: '查看蓝牙状态失败,请重新操作!',
                        icon: 'none',
                        duration: 1000
                    });
                })
            })
            .catch(e=>{
                console.log(e);
                wx.showToast({
                    title: '初始化失败,请打开蓝牙!',
                    icon: 'none',
                    duration: 1000
                });
            })		
        } else {  
            wx.showModal({  
                title: '提示',  
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'  
            })  
        }	
    },
    connectOperate:function(){
        wx.showLoading({
            title: '正在连接蓝牙',
            icon: 'loading',
            mask:true
        });

        var num = 0
        deviceId = this.data.deviceId;
        if(deviceId){
            console.log(deviceId);
            this.connection() 
            .then(res=>{
                console.log(res)
                wx.hideLoading()
                this.gainService()
                .then(res=>{
                    this.setData({
                        serviceId: res.services[0].uuid
                    })
                    this.gainValue()
                    .then(res=>{
                        console.log(res)
                        for (var i = 0; i < res.characteristics.length; i++) {  
                            if (res.characteristics[i].properties.notify) {  
                                this.setData({  
                                    notifyCharacteristicsId: res.characteristics[i].uuid,  
                                })  
                            }  
                            if (res.characteristics[i].properties.write) {  
                                this.setData({    
                                    writeCharacteristicsId: res.characteristics[i].uuid,  
                                })  
          
                            } else if (res.characteristics[i].properties.read) {  
                                this.setData({  
                                    readCharacteristicsId: res.characteristics[i].uuid,  
                                })  
          
                            }  
                        } 
                        this.setData({
                            display:true,
                            show:true
                        }) 
                    })
                    .catch(e=>{
                        console.log(e);
                    })
                })
                .catch(e=>{
                    console.log(e);
                })
            })
            .catch(e=>{
                console.log(e);
                wx.showToast({
                    title: '连接失败,请重启小程序',
                    icon: 'none',
                    duration: 1000
                });
            }) 
        }else{
            setTimeout(res=>{
                this.gainBlueTooth()
                .then(res=>{
                    console.log(res);
                    this.var_dump(res.devices);
                    if(num<=5){
                        this.connectOperate()    
                    }else{
                        wx.showToast({
                            title: '连接失败,请重启小程序',
                            icon: 'none',
                            duration: 1000
                        }); 
                    }
                })
                .catch(e=>{
                    console.log(e);
                    wx.showToast({
                        title: '获取设备失败,请重启小程序',
                        icon: 'none',
                        duration: 1000
                    });
                })
            },2000);
            num++;
        }
    },
    // 初始化蓝牙适配器
    blueInit: function () {  
        return new Promise((resolve, reject) => {
            wx.openBluetoothAdapter({
                success:resolve,
                fail:reject,
            }); 
        });
    },  
    // 本机蓝牙适配器状态
    blueStatus: function () {  
        return new Promise((resolve, reject) => {
            wx.getBluetoothAdapterState({
                success:resolve,
                fail:reject,
            }); 
        }); 
    },
    //搜索设备 
    searchBlueTooth: function () {  
        return new Promise((resolve, reject) => {
            wx.startBluetoothDevicesDiscovery({
                success:resolve,
                fail:reject,
            }); 
        });
    },
    // 获取所有已发现的设备  
    gainBlueTooth: function () {  
        return new Promise((resolve, reject) => {
            wx.getBluetoothDevices({
                success:resolve,
                fail:reject,
            }); 
        });
    },
    stopSearch: function () {  
        var that = this;  
        wx.stopBluetoothDevicesDiscovery({  
            success: function (res) {  
                that.setData({  
                    msg: "停止搜索周边设备" + "/" + JSON.stringify(res.errMsg),  
                    status: res.available ? "可用。" : "不可用。",  
                })  
            }  
        })  
    },    
    //连接蓝牙
    connection: function () {
        return new Promise((resolve, reject) => {
            wx.createBLEConnection({
                deviceId:this.data.deviceId,
                success:resolve,
                fail:reject,
            }); 
        });   
    },
    // 获取连接设备的service服务  
    gainService: function () {  
        return new Promise((resolve,reject) => {
            wx.getBLEDeviceServices({    
                deviceId: this.data.deviceId,  
                success:resolve,
                fail:reject,
            });  
        });
    },
    //获取连接设备的所有特征值 
    gainValue: function () {  
        return new Promise((resolve,reject)=>{
            wx.getBLEDeviceCharacteristics({
                deviceId: this.data.deviceId,
                serviceId: this.data.serviceId,
                success:resolve,
                fail:reject,
            })
           
        })
    },
    //发送  
    send: function (buf) {  
        var that = this;  
        // 这里的回调可以获取到 write 导致的特征值改变  
        wx.onBLECharacteristicValueChange(function (characteristic) {  
            console.log('characteristic value changed:1', characteristic)  
        })    
        wx.writeBLECharacteristicValue({  
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.deviceId,  
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: that.data.serviceId,  
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
            characteristicId: that.data.writeCharacteristicsId,  
            // 这里的value是ArrayBuffer类型  
            value: buf,  
            success: function (res) {  
                console.log('writeBLECharacteristicValue success', res.errMsg)
                // that.startUseBlue(); 
            }  
        })  
    },
    //启用低功耗蓝牙设备特征值变化时的 notify 功能  
    startUseBlue: function () {  
        var that = this;   
        wx.notifyBLECharacteristicValueChange({  
            state: true, // 启用 notify 功能  
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: this.data.deviceId,  
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: this.data.notifyServicweId,  
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
            characteristicId: that.data.notifyCharacteristicsId,  
            success: function (res) {  
                console.log('notifyBLECharacteristicValueChange success', res.errMsg);
                // that.accept(); 
            },  
            fail: function () {  
                console.log('shibai');  
                console.log(that.data.notifyServicweId);  
                console.log(that.data.notifyCharacteristicsId);  
            },  
        })  
    },
    //接收消息 
    accept: function () {  
        var that = this;  
        // 必须在这里的回调才能获取  
        wx.onBLECharacteristicValueChange(function (characteristic) {  
            let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');  
            console.log(hex)    
        })  
        console.log(that.data.readServicweId);  
        console.log(that.data.readCharacteristicsId);  
        wx.readBLECharacteristicValue({  
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,  
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: that.data.readServicweId,  
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
            characteristicId: that.data.readCharacteristicsId,  
            success: function (res) {  
                console.log('readBLECharacteristicValue:', res.errMsg);  
            }  
        })  
    },
    //断开设备连接  
    breakBlueTooth: function () {  
        var that = this;  
        wx.closeBLEConnection({  
            deviceId: that.data.deviceId,  
            success: function (res) {
                console.log(res);
                that.setData({
                    display:false,
                    show:false
                })
            }  
        })  
    },    
    var_dump:function (event) {
        var equipment_id = this.data.equipment_id;
        String.prototype.trim = function () { 
            return this.replace(/^0+/, "");
        }
        var blueToothId = equipment_id.trim();
        for(var i=0;i<event.length;i++){
            if(event[i]['name'] == blueToothId){
                this.setData({deviceId:event[i]['deviceId']});
            }  
        }
    }
})